package com.zlz.news.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.zlz.common.OpenToken;
import com.zlz.news.constant.Constants;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author wangl
 * @desc
 * @date:2017/7/514:38
 * @Copyright (c) 2017, DaChen All Rights Reserved.
 */
public class CacheUtil {


    private static final LoadingCache<String,String> cache= CacheBuilder
        .newBuilder()
        .maximumSize(2000)
        .build(new CacheLoader<String, String>() {
            public String load(String key) throws Exception {
                if (RequestContextHolder.getRequestAttributes() == null)
                    return null;
                HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                if(req == null)
                    return null;
                return req.getHeader(Constants.HEADER_TOKEN_KEY);
            }
        });

    public static void put(String k, String v){
        cache.put(k, v);
    }

    public static String get(String k){
        return cache.getIfPresent(k);
    }

    public static OpenToken getOpenToken(String k) {
        String jsonT = get(k);
        if(StringUtils.isBlank(jsonT))
            return null;
        return JSONObject.parseObject(jsonT, OpenToken.class);
    }

    public static String getUserId(String k){
        OpenToken token = getOpenToken(k);
        if(Objects.isNull(token))
            return null;
        return token.getUserId();
    }

}
